/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* $Id: rtc.c 20 2007-07-11 09:51:35Z kf701.ye $ */

#include "factory.h"

#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

time_t get_rtc_time(char *rtc_dev)
{
	int fd, retval;
	struct rtc_time rtc_tm;

	fd = open (rtc_dev, O_RDONLY);
	if ( fd == -1)
	{
		sys_message("open RTC: %m\n");
		return -1;
	}

	retval = ioctl(fd, RTC_RD_TIME, &rtc_tm);
	if (retval == -1)
	{
		close(fd);
		return -1;
	}
	close(fd);
	return mktime( (struct tm*)&rtc_tm );
}

bool set_rtc_time(char *rtc_dev, time_t time)
{
	int fd, retval;
	struct rtc_time *rtc_tm = (struct rtc_time*)gmtime(&time);

	fd = open (rtc_dev, O_RDONLY);
	if ( fd == -1)
	{
		sys_message("open RTC: %m\n");
		return false;
	}

	retval = ioctl(fd, RTC_SET_TIME, rtc_tm);
	if (retval == -1)
	{
		close(fd);
		return false;
	}
	close(fd);
	return true;
}
